<template>
  <view class="merchant-audit-container">
    <view class="header-actions">
      <view class="search-box">
        <uni-easyinput
          v-model="searchKeyword"
          placeholder="搜索商家名称"
          @input="handleSearch"
        />
      </view>
      <view class="filter-box">
        <uni-data-select
          v-model="statusFilter"
          :localdata="statusOptions"
          @change="handleStatusChange"
        />
      </view>
    </view>

    <view class="merchant-list">
      <uni-table stripe emptyText="暂无数据">
        <uni-tr>
          <uni-th align="center">商家名称</uni-th>
          <uni-th align="center">联系人</uni-th>
          <uni-th align="center">联系电话</uni-th>
          <uni-th align="center">申请时间</uni-th>
          <uni-th align="center">状态</uni-th>
          <uni-th align="center">操作</uni-th>
        </uni-tr>
        <uni-tr v-for="item in merchantList" :key="item._id">
          <uni-td>{{ item.base?.merchantName }}</uni-td>
          <uni-td>{{ item.base?.contactPerson }}</uni-td>
          <uni-td>{{ item.base?.phone }}</uni-td>
          <uni-td>{{ formatDate(item.createTime) }}</uni-td>
          <uni-td>
            <uni-tag :type="getStatusType(item.status)" :text="getStatusText(item.status)" />
          </uni-td>
          <uni-td>
            <view class="action-buttons">
              <button 
                class="btn-view"
                size="mini" 
                @click="openAuditModal(item)"
              >查看详情</button>
              <button 
                class="btn-delete"
                size="mini" 
                type="warn"
                @click="confirmDelete(item)"
              >删除</button>
            </view>
          </uni-td>
        </uni-tr>
      </uni-table>
      
      <view class="pagination">
        <uni-pagination
          show-icon
          :total="total"
          :pageSize="pageSize"
          :current="currentPage"
          @change="handlePageChange"
        />
      </view>
    </view>

    <!-- 审核弹窗 -->
    <uni-popup ref="auditPopup" type="dialog">
      <view class="audit-modal">
        <view class="modal-header">
          <text class="title">商家资质审核</text>
          <text class="close" @click="closeAuditModal">×</text>
        </view>
        <view class="modal-body">
          <view class="info-section">
            <view class="info-item">
              <text class="label">商家名称：</text>
              <text class="value">{{ currentMerchant?.base?.merchantName }}</text>
            </view>
            <view class="info-item">
              <text class="label">联系人：</text>
              <text class="value">{{ currentMerchant?.base?.contactPerson }}</text>
            </view>
            <view class="info-item">
              <text class="label">联系电话：</text>
              <text class="value">{{ currentMerchant?.base?.phone }}</text>
            </view>
            <view class="info-item">
              <text class="label">电子邮箱：</text>
              <text class="value">{{ currentMerchant?.base?.email }}</text>
            </view>
          </view>
          
          <view class="images-section">
            <view class="image-item">
              <text class="image-label">手持身份证人像</text>
              <image 
                :src="currentMerchant?.qualification?.businessLicense?.[0]?.url" 
                mode="aspectFit"
                @click="previewImage(currentMerchant?.qualification?.businessLicense?.[0]?.url)"
              />
            </view>
            <view class="image-item">
              <text class="image-label">身份证正面</text>
              <image 
                :src="currentMerchant?.qualification?.idCardFront?.[0]?.url" 
                mode="aspectFit"
                @click="previewImage(currentMerchant?.qualification?.idCardFront?.[0]?.url)"
              />
            </view>
            <view class="image-item">
              <text class="image-label">身份证反面</text>
              <image 
                :src="currentMerchant?.qualification?.idCardBack?.[0]?.url" 
                mode="aspectFit"
                @click="previewImage(currentMerchant?.qualification?.idCardBack?.[0]?.url)"
              />
            </view>
          </view>

          <view class="other-qualifications" v-if="currentMerchant?.qualification?.otherQualifications?.length">
            <text class="section-title">其他资质</text>
            <view class="images-grid">
              <view 
                v-for="(item, index) in currentMerchant.qualification.otherQualifications" 
                :key="index" 
                class="image-item"
              >
                <image 
                  :src="item.url" 
                  mode="aspectFit"
                  @click="previewImage(item.url)"
                />
              </view>
            </view>
          </view>

          <view class="audit-form" v-if="currentMerchant?.status === 'pending'">
            <view class="form-item">
              <text class="label">审核结果</text>
              <radio-group @change="handleAuditResultChange">
                <label class="radio">
                  <radio value="approved" /><text>通过</text>
                </label>
                <label class="radio">
                  <radio value="rejected" /><text>拒绝</text>
                </label>
              </radio-group>
            </view>
            <view class="form-item" v-if="auditResult === 'rejected'">
              <text class="label">拒绝原因</text>
              <uni-easyinput
                type="textarea"
                v-model="rejectReason"
                placeholder="请输入拒绝原因"
              />
            </view>
          </view>
        </view>
        <view class="modal-footer" v-if="currentMerchant?.status === 'pending'">
          <button 
            class="btn-cancel" 
            @click="closeAuditModal"
          >取消</button>
          <button 
            class="btn-submit" 
            type="primary" 
            @click="submitAudit"
            :disabled="!canSubmitAudit"
          >提交审核</button>
        </view>
      </view>
    </uni-popup>
    
    <!-- 删除确认弹窗 -->
    <uni-popup ref="deletePopup" type="dialog">
      <uni-popup-dialog
        title="删除确认"
        content="确定要删除此商家申请记录吗？此操作不可恢复。"
        confirmText="删除"
        cancelText="取消"
        @confirm="deleteMerchant"
        @close="closeDeletePopup"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

// 状态选项
const statusOptions = [
  { value: 'all', text: '全部状态' },
  { value: 'pending', text: '待审核' },
  { value: 'approved', text: '已通过' },
  { value: 'rejected', text: '已拒绝' }
]

// 列表相关数据
const searchKeyword = ref('')
const statusFilter = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const merchantList = ref([])

// 当前审核的商家
const currentMerchant = ref(null)
const auditResult = ref('')
const rejectReason = ref('')
const auditPopup = ref(null)
const deletePopup = ref(null)
const merchantToDelete = ref(null)

// 计算属性：是否可以提交审核
const canSubmitAudit = computed(() => {
  if (auditResult.value === 'approved') return true
  if (auditResult.value === 'rejected' && rejectReason.value.trim()) return true
  return false
})

// 获取商家列表
const fetchMerchantList = async () => {
  try {
    uni.showLoading({
      title: '加载中...'
    })
    
    const res = await uniCloud.callFunction({
      name: 'alldata',
      data: {
        body: JSON.stringify({
          action: 'getMerchantList',
          keyword: searchKeyword.value,
          status: statusFilter.value === 'all' ? '' : statusFilter.value,
          page: currentPage.value,
          pageSize: pageSize.value
        })
      }
    })
    
    uni.hideLoading()
    
    if (res.result && res.result.code === 0) {
      merchantList.value = res.result.data || []
      total.value = res.result.total || 0
    } else {
      uni.showToast({
        title: res.result?.message || '获取数据失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.hideLoading()
    console.error('获取数据失败：', error)
    uni.showToast({
      title: '获取数据失败',
      icon: 'none'
    })
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchMerchantList()
}

// 处理状态筛选
const handleStatusChange = () => {
  currentPage.value = 1
  fetchMerchantList()
}

// 处理分页
const handlePageChange = (e) => {
  currentPage.value = e.current
  fetchMerchantList()
}

// 打开审核弹窗
const openAuditModal = (merchant) => {
  currentMerchant.value = merchant
  auditResult.value = ''
  rejectReason.value = ''
  auditPopup.value.open()
}

// 关闭审核弹窗
const closeAuditModal = () => {
  auditPopup.value.close()
  currentMerchant.value = null
}

// 处理审核结果选择
const handleAuditResultChange = (e) => {
  auditResult.value = e.detail.value
  if (auditResult.value === 'approved') {
    rejectReason.value = ''
  }
}

// 提交审核
const submitAudit = async () => {
  try {
    uni.showLoading({
      title: '提交中...'
    })
    
    // 使用alldata云函数的updateMerchant方法
    const result = await uniCloud.callFunction({
      name: 'alldata',
      data: {
        body: JSON.stringify({
          action: 'updateMerchant',
          merchantId: currentMerchant.value._id,
          data: {
            status: auditResult.value,
            auditTime: Date.now(),
            rejectReason: auditResult.value === 'rejected' ? rejectReason.value : '',
            auditor: getApp().globalData.userInfo?.username || '管理员'
          }
        })
      }
    })

    uni.hideLoading()
    
    if (result.result && result.result.code === 0) {
      uni.showToast({
        title: '审核成功',
        icon: 'success'
      })
      closeAuditModal()
      fetchMerchantList()
    } else {
      uni.showToast({
        title: result.result?.message || '审核失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.hideLoading()
    console.error('审核提交失败:', error)
    uni.showToast({
      title: '审核失败',
      icon: 'none'
    })
  }
}

// 预览图片
const previewImage = (url) => {
  if (!url) return
  uni.previewImage({
    urls: [url]
  })
}

// 格式化日期
const formatDate = (timestamp) => {
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    pending: 'warning',
    approved: 'success',
    rejected: 'error'
  }
  return types[status] || 'default'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return texts[status] || '未知'
}

// 确认删除商家
const confirmDelete = (merchant) => {
  merchantToDelete.value = merchant
  deletePopup.value.open()
}

// 关闭删除弹窗
const closeDeletePopup = () => {
  deletePopup.value.close()
  merchantToDelete.value = null
}

// 删除商家
const deleteMerchant = async () => {
  if (!merchantToDelete.value || !merchantToDelete.value._id) {
    uni.showToast({
      title: '删除失败：无效的商家ID',
      icon: 'none'
    })
    return
  }
  
  try {
    uni.showLoading({
      title: '删除中...'
    })
    
    const result = await uniCloud.callFunction({
      name: 'alldata',
      data: {
        body: JSON.stringify({
          action: 'deleteMerchant',
          merchantId: merchantToDelete.value._id
        })
      }
    })
    
    uni.hideLoading()
    
    if (result.result && result.result.code === 0) {
      uni.showToast({
        title: '删除成功',
        icon: 'success'
      })
      fetchMerchantList()
    } else {
      uni.showToast({
        title: result.result?.message || '删除失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.hideLoading()
    console.error('删除商家失败:', error)
    uni.showToast({
      title: '删除失败',
      icon: 'none'
    })
  } finally {
    closeDeletePopup()
  }
}

// 初始化
onMounted(() => {
  fetchMerchantList()
})
</script>

<style lang="scss" scoped>
.merchant-audit-container {
  padding: 20rpx;

  .header-actions {
    display: flex;
    gap: 20rpx;
    margin-bottom: 20rpx;

    .search-box {
      flex: 1;
    }

    .filter-box {
      width: 200rpx;
    }
  }

  .merchant-list {
    background-color: #fff;
    border-radius: 8rpx;
    padding: 20rpx;

    .action-buttons {
      display: flex;
      justify-content: center;
      gap: 10rpx;
      
      .btn-view, .btn-delete {
        font-size: 24rpx;
        padding: 8rpx 20rpx;
      }
      
      .btn-delete {
        background-color: #ff4d4f;
        color: #fff;
      }
    }
  }

  .pagination {
    margin-top: 20rpx;
    display: flex;
    justify-content: center;
  }
}

.audit-modal {
  background-color: #fff;
  border-radius: 8rpx;
  width: 90vw;
  max-width: 800rpx;

  .modal-header {
    padding: 20rpx;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 32rpx;
      font-weight: bold;
    }

    .close {
      font-size: 40rpx;
      cursor: pointer;
    }
  }

  .modal-body {
    padding: 20rpx;
    max-height: 70vh;
    overflow-y: auto;

    .info-section {
      margin-bottom: 30rpx;

      .info-item {
        margin-bottom: 10rpx;
        display: flex;
        
        .label {
          width: 160rpx;
          color: #666;
        }
      }
    }

    .images-section {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 20rpx;
      margin-bottom: 30rpx;

      .image-item {
        .image-label {
          display: block;
          margin-bottom: 10rpx;
          color: #666;
        }

        image {
          width: 100%;
          height: 300rpx;
          border: 1px solid #eee;
          border-radius: 4rpx;
        }
      }
    }

    .other-qualifications {
      margin-top: 30rpx;
      
      .section-title {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 20rpx;
        display: block;
      }
      
      .images-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 20rpx;
        
        .image-item {
          image {
            width: 100%;
            height: 200rpx;
            border: 1px solid #eee;
            border-radius: 4rpx;
          }
        }
      }
    }

    .audit-form {
      .form-item {
        margin-bottom: 20rpx;

        .label {
          display: block;
          margin-bottom: 10rpx;
          color: #666;
        }

        .radio {
          margin-right: 30rpx;
        }
      }
    }
  }

  .modal-footer {
    padding: 20rpx;
    border-top: 1px solid #eee;
    display: flex;
    justify-content: flex-end;
    gap: 20rpx;

    button {
      min-width: 180rpx;
    }
  }
}

.images-section {
  .image-item {
    image {
      cursor: pointer;
      transition: transform 0.3s;
      
      &:hover {
        transform: scale(1.02);
      }
    }
  }
}
</style> 